# -*- coding: utf-8 -*-

'''eof
name:申请企业信用评级校验
code:R69_EntCreditRatingCheck_ZC
tableName:
columnName:
groups:企业业务信息校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')


def formatDate(time):
    try:
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None


def getRule69():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    entCreditLevel = json.loads(ratingRequest.get("entCreditLevel"))
    creditLevelList = ['AAA+', 'AAA', 'AAA-', 'AA+', 'AA', 'AA-', 'A+', 'A', 'A-', 'BBB']
    if entCreditLevel not in null_type_list:
        creditLevel = entCreditLevel.get("creditLevel")
        starDate = entCreditLevel.get("starDate")
        endDate = entCreditLevel.get("endDate")
        # inputDate = entCreditLevel.get("inputDate")
        inputDate = datetime.datetime.now().strftime('%Y%m%d')
        if creditLevel in null_type_list and starDate in null_type_list and endDate in null_type_list:
            raise RuntimeError("客户未作评级")
        if creditLevel not in null_type_list and starDate not in null_type_list and endDate not in null_type_list \
                and inputDate not in null_type_list:
            starDate = formatDate(starDate)
            endDate = formatDate(endDate)
            inputDate = formatDate(inputDate)
            if starDate <= inputDate <= endDate:
                if creditLevel in creditLevelList:
                    return 1
                else:
                    return 0
            else:
                raise RuntimeError("客户需重新评级")
        else:
            raise RuntimeError("客户数据有必传字段为空")

    else:
        raise RuntimeError("网贷传输的数据企业信用评级信息错误或者为空")


if __name__ == "__main__":
    file_obj = open(r'../data/rating/R04_EG_IndLimitCheck/CQB_DSJ.json', 'r')
    content = file_obj.read()
    CQB_DSJ = json.loads(content, strict=False)
    aa = getRule69()
    print aa

result = getRule69()
